const express = require("express");
const router = express.Router();
const Classify = require("../data/models/Classify");
const User = require("../data/models/User");
const Document = require("../data/models/Document");
const jwt = require("../controller/jwt");
const Search = require("../controller/Search");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
module.exports = router;

router
  .route("/")
  .get(jwt.check, async (req, res) => {
    let form = req.query;
    Search.Get(Document, { title: { $regex: form.title } }, req, res, "classify", "tag");
  })
  .post(jwt.check, (req, res) => {
    if (req.body != undefined && JSON.stringify(req.body) != "{}") {
      Document.findOne({ title: req.body.title, user: req.user }, (err, doc) => {
        if (err) res.status(500).send(err);
        if (doc) res.send({ Code: 500, Msg: "已存在文档" });
        else {
          Document.create({ ...req.body, user: req.user }, err => {
            if (err) res.status(500).send(err);
            res.send({ Code: 200, Msg: "新增成功" });
          });
        }
      });
    } else res.send({ Code: 500, Msg: "新增失败" });
  })
  .put(jwt.check, (req, res) => {
    if (req.body != undefined && JSON.stringify(req.body) != "{}") {
      // let { title, classify, tag } = req.body;
      // let record = [...new Set(tag)]; // 去重  前端已去重

      Document.findByIdAndUpdate(req.body._id, req.body, err => {
        if (err) res.status(500).send(err);
        res.send({ Code: 200, Msg: "修改成功" });
      });
    } else res.send({ Code: 500, Msg: "新增失败" });
  })
  .delete(jwt.check, (req, res) => {
    Document.findOneAndDelete(req.query, err => {
      if (err) res.status(500).send(err);
      res.send({ Code: 200, Msg: "删除成功" });
    });
  });

const upDocImg = multer({ dest: "public/images/doc" });
router.post("/uploadImg", jwt.check, upDocImg.single("DocImg"), (req, res) => {
  let original = req.file.originalname.split(".");
  original.splice(-1, 0, new Date().getTime());
  let NewName = original.join(".");
  let newPath = path.join(req.file.path, "../", NewName);
  fs.rename(req.file.path, newPath, err => {
    if (err) res.send(err);
    let url = "images/doc/" + NewName;
    res.send({ Code: 200, Msg: "文档图片上传成功", Data: url });
  });
});
